using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Terra.Core.Common.Utils;
using Terra.Data.Repository.Identity;
using Terra.Data.Models.Identity;
using Terra.Service.Identity.Interfaces;
using Terra.Core.Common.ApiResponse;

namespace Terra.Service.Identity.Implementations;

/// <summary>
/// 权限服务实现
/// </summary>
public class PermissionService : IPermissionService
{
    private readonly IPermissionRepository _permissionRepository;
    private readonly IMapper _mapper;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="permissionRepository">权限仓储</param>
    /// <param name="mapper">对象映射器</param>
    public PermissionService(IPermissionRepository permissionRepository, IMapper mapper)
    {
        _permissionRepository = permissionRepository;
        _mapper = mapper;
    }

    /// <summary>
    /// 获取用户菜单列表
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>菜单列表</returns>
    public async Task<ApiResponse<List<MenuTreeDto>>> GetUserMenusAsync(Guid userId)
    {
        // 从仓储层获取菜单列表
        var menus = await _permissionRepository.GetUserMenusAsync(userId);

        // 转换为DTO
        var menuDtos = _mapper.Map<List<MenuTreeDto>>(menus);

        // 构建树形结构
        var tree = TreeUtils.BuildTree(
            menuDtos,
            m => m.Id,
            m => m.ParentId != null ? m.ParentId.Value : default,
            m => m.Children ?? new List<MenuTreeDto>(),
            m => m.ParentId == null);
        return ApiResponse<List<MenuTreeDto>>.Success(tree);
    }

    /// <summary>
    /// 获取用户权限码列表
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <returns>权限码列表</returns>
    public async Task<ApiResponse<List<string>>> GetUserPermissionCodesAsync(Guid userId)
    {
        var data = await _permissionRepository.GetUserPermissionCodesAsync(userId);
        return ApiResponse<List<string>>.Success(data);
    }
}